# _*_ coding utf-8 _*_
# george
# time: 2025/1/11下午1:58
# name: user.py
# comment:
import json

from flask import Blueprint, request, render_template, session, redirect, make_response, url_for, jsonify

from model.role import Role
from model.team import Team
from model.user import User
import app.config.config
import logging
from app.settings import login_required

user_logger = logging.getLogger("User的View视图:")

user = Blueprint("user", __name__)


@user.route("/", methods=["GET", "POST"])
@user.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        session.clear()
        return render_template("login.html")
    username = request.form.get("username").strip()
    password = request.form.get("password").strip()
    if not user or not password:
        return render_template("login.html", error="账号或密码不能为空!!")
    # 连接数据库进行数据库校验
    result = User().login_verify(username, password)
    user_logger.debug(f"获取校验结果{result}")
    if not result:
        return render_template("login.html", error="账号或是密码错误!!")
    if not result.user_exit:
        return render_template("login.html", error="系统权限被移除,请联系管理员!!")
    # 将用户信息存储到cookie里面去, 在flask的内部会对数据进行加密, 类似于加盐的操作
    session["user_info"] = {"isLogin": True, "username": result.username, "password": result.password,
                            "job_n": result.job_n, "role": result.role_id, 'user_exit': result.user_exit}
    user_logger.info(f"{session['user_info'].get('username')}登陆系统!!")
    return redirect("/home")

    # if user_info:
    #     # 将用户信息存储到cookie里面去,在flask的内部会对数据进行加密,类似于加盐的操作
    #     session["user_info"] = {"id": user_info.id, "username": user_info.username,
    #                             "mobile": user_info.mobile, "role": user_info.role}
    #     if user_info.role == 1 or user_info.role == 0:
    #         return redirect("/common/home")  # 跳转到主页面
    #     else:
    #         return "您暂时无权限登录该系统！！"

    # return render_template('login.html', title='Sign In', form=form)


@user.route("/logout")
def logout():
    # 清空session
    session.clear()
    response = make_response("注销登陆", 302)
    # url_for(路由名称.函数名)
    response.headers["Location"] = url_for("user.login")
    return response


@user.route("/staff")
@login_required
def get_staff():
    staffs = User().get_all_users()
    roles = Role().search_role()
    teams = Team().search_team()
    return render_template("/staff.html", staffs=staffs,roles=roles,teams=teams)


@user.route("/staff/update-status/", methods=["GET", "POST"])
@login_required
def update_staff_status():
    # 从请求中获取JSON数据
    data = request.get_json()
    # 检查是否成功获取到数据
    if not data:
        return jsonify({'message': 'fail'})
    id, status = data.values()
    res = User().change_user_status(id, status)
    if not res:
        return jsonify({'message': 'fail'})
    return jsonify({'message': 'success'})

# 添加用户
@user.route("/staff/add-user/", methods=["GET", "POST"])
@login_required
def add_user():
    # 从请求中获取JSON数据
    data = request.get_json()
    # 检查是否成功获取到数据
    if not data:
        return jsonify({'message': 'fail'})
    job_n, username,password,team_id,role_id = data.values()
    res = User().add_user(job_n, username,password,team_id,role_id)
    if not res:
        return jsonify({'message': 'fail'})
    return jsonify({'message': 'success'})

# 删除用户
@user.route("/staff/delete-user/", methods=["GET", "POST"])
@login_required
def delete_user():
    # 从请求中获取JSON数据
    data = request.get_json()
    # 检查是否成功获取到数据
    if not data:
        return jsonify({'message': 'fail'})
    user_id = data.get("id")
    res = User().drop_user(user_id)
    if not res:
        return jsonify({'message': 'fail'})
    return jsonify({'message': 'success'})

# 编辑用户
@user.route("/staff/edit-user/",methods=["GET", "POST"])
@login_required
def edit_user():
    if request.method == "GET":
        # 从URL获取用户ID
        user_id = request.args.get('id')
        if not user_id:
            return jsonify({'message': 'fail'})
            
        # 获取用户信息
        user_info = User().get_user_info(user_id)
        if not user_info:
            return jsonify({'message': 'fail'})
            
        # 返回用户信息
        return jsonify({
            'name': user_info.username,
            'workNum': user_info.job_n,
            "password": user_info.password,
            'role': user_info.role_id,
            'team': user_info.team_id
        })
        
    elif request.method == "POST":
        # 从请求中获取JSON数据
        data = request.get_json()
        if not data:
            return jsonify({'message': 'fail'})
            
        # 获取更新的用户信息
        user_id = data.get('id')
        name = data.get('name')
        work_num = data.get('workNum') 
        password = data.get('password')
        role_id = data.get('role')
        team_id = data.get('team')
        
        # 更新用户信息
        res = User().update_user(user_id, name, work_num, password,  team_id,role_id)
        print(res,"res")
        if not res:
            return jsonify({'message': 'fail'})
            
        return jsonify({'message': 'success'})